package com.rsc.learningbar.websocket;

import com.rsc.learningbar.service.WebSocketPlanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@Component
@ServerEndpoint("/studyPlan/{userid}")
@Slf4j
public class StudyPlanServerEndpoint {

    /**
     * 打开
     *
     * @param userid
     * @param session
     */
    @OnOpen
    public void openSession(@PathParam("userid") Long userid, Session session) {
        // 发sesson
        WebSocketPlanService.ONLINE_USER_SESSIONS.put(userid, session);
//        sendMessage(session, "服务器连接成功！");
        WebSocketPlanService.setPlanQueue(userid);

        log.info("openSession:" + userid + "连接成功");
    }

    @OnMessage
    public void onMessage(@PathParam("userid") String userid, String message) {
//        sendMessageAll("[" + userid + "] : " + message);
    }

    /**
     * 关闭
     *
     * @param userid
     * @param session
     */
    @OnClose
    public void onClose(@PathParam("userid") String userid, Session session) {
        //当前的Session 移除
        WebSocketPlanService.ONLINE_USER_SESSIONS.remove(userid);
        //并且通知其他人当前用户已经断开连接了
        log.info("[" + userid + "] 断开连接！");
        try {
            session.close();
        } catch (IOException e) {
        }
    }

    /**
     * 发生错误
     *
     * @param session
     * @param throwable
     */
    @OnError
    public void onError(Session session, Throwable throwable) {
        try {
            session.close();
        } catch (IOException e) {
        }
    }
}
